<template>
  <div class="exam-container">
    <el-card class="exam-card">
      <template #header>
        <div class="card-header">
          <h3>考试管理</h3>
        </div>
      </template>

      <!-- 考试列表 -->
      <el-table
        :data="exams"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
        stripe>
        <el-table-column prop="title" label="考试标题" min-width="200">
          <template #default="{ row }">
            <div class="exam-title">
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="exam_date" label="考试日期" width="180">
          <template #default="{ row }">
            <div class="exam-date">
              <i class="el-icon-time"></i>
              {{ formatDate(row.exam_date) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                type="primary"
                size="small"
                @click="openUploadScanDialog(row.id)">
                试卷上传/评分
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewExamDetail(row.id)">
                查看详情
              </el-button>
              <el-dropdown>
                <el-button size="small">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openEditDialog(row)">
                      <i class="el-icon-edit"></i> 编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="confirmDeleteExam(row.id)"
                      class="delete-option">
                      <i class="el-icon-delete"></i> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="openCreateDialog" class="create-btn">
        创建新考试
      </el-button>
    </el-card>

    <!-- 创建/编辑考试表单弹窗 -->
    <ExamFormDialog
      v-model:visible="formDialogVisible"
      v-model:form="examForm"
      :is-edit="isEdit"
      v-model:fileList="examForm.files"
      v-model:answerFileList="examForm.answer_files"
      @submit="submitExam"
    />


    <!-- 创建/编辑考试表单弹窗 -->
    <ExamFormDialog
  v-model:visible="formDialogVisible"
  v-model:form="examForm"
  :is-edit="isEdit"
  v-model:fileList="examForm.files"
  v-model:answerFileList="examForm.answer_files"
  :examAttachments="existingAttachments"
  :answerAttachments="existingAnswerAttachments"
  @submit="submitExam"
/>

    <!-- 考试详情弹窗 -->
    <ExamDetailDialog
      v-model:visible="detailDialogVisible"
      :exam="examDetail"
      @close="handleCloseDetailDialog"
    />
      <!-- 考试提交列表对话框 -->
  <ExamSubmissionDialog
    v-model:visible="submissionDialogVisible"
    :submissions="submissionList"
    @close="submissionDialogVisible = false"
    @upload-scan="handleUploadScan"
    @grade="handleGrade"
    @view="handleViewSubmission"
  />

  <!-- 上传试卷扫描件对话框 -->
  <UploadScanDialog
    v-model:visible="uploadScanDialogVisible"
    :exam-id="currentExamId"
    :submission="currentSubmission"
    @uploaded="handleUploadedScan"
  />

  <!-- 评分对话框 -->
  <ExamGradingDialog
    v-model:visible="gradingDialogVisible"
    :submission="currentSubmission"
    @graded="handleGraded"
  />

  <!-- 提交详情对话框 -->
  <ExamSubmissionDetailDialog
    v-model:visible="submissionDetailDialogVisible"
    :submission="currentSubmission"
  />

<!-- 考试提交列表对话框 -->
<ExamSubmissionDialog
  v-model:visible="submissionDialogVisible"
  :submissions="submissionList"
  @close="submissionDialogVisible = false"
  @upload-scan="handleUploadScan"
  @grade="handleGrade"
  @view="handleViewSubmission"
/>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      center>
      <div class="delete-confirmation">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除这个考试吗？此操作无法撤销。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="deleteExam">确定删除</el-button>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Timer, Edit, Delete, Warning } from '@element-plus/icons-vue'
import ExamDetailDialog from '@/components/exam/ExamDetailDialog.vue'
import UploadScanDialog from '@/components/exam/UploadScanDialog.vue'
import ExamFormDialog from '@/components/exam/ExamFormDialog.vue'
import ExamSubmissionDialog from "@/components/exam/ExamSubmissionDialog.vue";
import ExamGradingDialog from '@/components/exam/ExamGradingDialog.vue'
import ExamSubmissionDetailDialog from '@/components/exam/ExamSubmissionDetailDialog.vue'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})
const existingAttachments = ref([])
const existingAnswerAttachments = ref([])
const submissionDialogVisible = ref(false)
const gradingDialogVisible = ref(false)
const submissionDetailDialogVisible = ref(false)
const submissionList = ref([])
const currentSubmission = ref(null)
const examToDelete = ref(null)
const exams = ref([])
const loading = ref(false)
const currentExamId = ref(null)
const examDetail = ref(null)
const uploadScanDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const isEdit = ref(false)
const examForm = reactive({
  id: null,
  title: '',
  description: '',
  exam_date: '',
  classroom: '',
  seating_type: '',
  files: [],
  answer_files: []
})

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 添加状态处理函数
const getStatusType = (status) => {
  const statusMap = {
    'NOT_STARTED': 'info',
    'IN_PROGRESS': 'warning',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status) => {
  const statusMap = {
    'NOT_STARTED': '未开始',
    'IN_PROGRESS': '进行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 状态相关的计算函数
const computeExamStatus = (examDate) => {
  const now = new Date();
  const examTime = new Date(examDate);
  if (examTime > now) {
    return 'NOT_STARTED';
  } else if (examTime <= now && examTime.getTime() + 24 * 60 * 60 * 1000 > now.getTime()) {
    return 'IN_PROGRESS';
  } else {
    return 'COMPLETED';
  }
};


// 修改获取考试列表的函数
const fetchExams = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/backend/api/exam/course/${props.courseId}/list/`, {
      withCredentials: true
    })
    if (Array.isArray(response.data)) {
      // 确保所有考试数据都有完整的属性
      exams.value = response.data.map(exam => ({
        ...exam,
        status: exam.status || computeExamStatus(exam.exam_date)
      }));
    } else {
      console.error('返回数据格式错误:', response.data)
      exams.value = []
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败，请稍后重试')
    exams.value = []
  } finally {
    loading.value = false
  }
}

// ExamTeacher.vue 中相关的修改
const openSubmissionDialog = async (examId) => {
  try {
    // 获取考试提交状态列表
    const response = await fetch(`/backend/api/exam/${examId}/submission_status/`);
    if (!response.ok) throw new Error('Failed to fetch submissions');
    const submissionList = await response.json();

    setSubmissions(submissionList);
    setSubmissionDialogOpen(true);
  } catch (error) {
    // 处理错误
  }
};

const openCreateDialog = () => {
  isEdit.value = false
  Object.assign(examForm, {
    id: null,
    title: '',
    description: '',
    exam_date: '',
    classroom: '',
    seating_type: '',
    files: [],
    answer_files: []
  })
  formDialogVisible.value = true
}

const openEditDialog = async (exam) => {
  isEdit.value = true;
  try {
    // 像考试详情一样获取完整信息
    const response = await axios.get(`/backend/api/exam/${exam.id}/`, {
      withCredentials: true,
    });

    const examDetail = response.data;
    // 使用获取到的完整信息填充表单
    Object.assign(examForm, {
      id: examDetail.id,
      title: examDetail.title,
      description: examDetail.description,
      exam_date: examDetail.exam_date,
      classroom: examDetail.classroom,
      seating_type: examDetail.seating_type,
      files: [], // 新上传的文件
      answer_files: [] // 新上传的答案文件
    });

    // 传递现有附件到表单对话框组件
    existingAttachments.value = response.data.attachments || [];
    existingAnswerAttachments.value = response.data.answer_attachments || [];
  } catch (error) {
    console.error('获取考试详情失败:', error);
    ElMessage.error('获取考试详情失败，请稍后重试');
    return;
  }

  formDialogVisible.value = true;
};

const submitExam = async () => {
  try {
    const url = isEdit.value
      ? `/backend/api/exam/${examForm.id}/update/`
      : '/backend/api/exam/create/';

    const requestData = {
      course: props.courseId,
      title: examForm.title,
      description: examForm.description,
      exam_date: new Date(examForm.exam_date).toISOString(),
      classroom: examForm.classroom,
      seating_type: examForm.seating_type,
    };

    const response = await axios({
      method: isEdit.value ? 'patch' : 'post',
      url: url,
      data: requestData,
      headers: { 'Content-Type': 'application/json' },
      withCredentials: true,
    });

    const examId = isEdit.value ? examForm.id : response.data.id;

    // 并行上传所有文件
    const uploadTasks = [];

    if (examForm.files.length > 0) {
      uploadTasks.push(uploadAttachments(examId, 'exam'));
    }

    if (examForm.answer_files.length > 0) {
      uploadTasks.push(uploadAttachments(examId, 'answer'));
    }

    // 等待所有上传完成
    await Promise.allSettled(uploadTasks).then(results => {
      results.forEach((result, index) => {
        if (result.status === 'rejected') {
          ElMessage.warning(`${index === 0 ? '考试' : '答案'}附件上传失败，请稍后在编辑中重试`);
        }
      });
    });

    ElMessage.success(isEdit.value ? '考试更新成功' : '考试创建成功');
    formDialogVisible.value = false;
    fetchExams();
  } catch (error) {
    console.error(`${isEdit.value ? '更新考试' : '创建考试'}失败:`, error);
    ElMessage.error(`${isEdit.value ? '更新考试' : '创建考试'}失败，请稍后重试`);
  }
};

const uploadAttachments = async (examId, attachmentType) => {
  const formData = new FormData();
  const filesToUpload = attachmentType === 'exam' ? examForm.files : examForm.answer_files;

  filesToUpload.forEach(file => {
    formData.append('files', file.raw);
  });

  try {
    const response = await axios.post(
      `/backend/api/exam/${examId}/upload_attachments/?attachment_type=${attachmentType}`,
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        withCredentials: true,
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          ElMessage({
            message: `${attachmentType === 'exam' ? '考试' : '答案'}附件上传进度: ${percentCompleted}%`,
            type: 'info',
            duration: 1000
          });
        }
      }
    );
    return response.data;
  } catch (error) {
    console.error('上传附件失败:', error);
    throw new Error(`上传${attachmentType === 'exam' ? '考试' : '答案'}附件失败`);
  }
};

const handleRemoveAttachment = async (attachmentId, attachmentType) => {
  try {
    await axios.delete(`/backend/api/exam/attachment/${attachmentId}/delete/?attachment_type=${attachmentType}`, {
      withCredentials: true,
    });
    existingAttachments.value = existingAttachments.value.filter(
      attachment => attachment.id !== attachmentId
    );
    ElMessage.success('附件删除成功');
  } catch (error) {
    console.error('删除附件失败:', error);
    ElMessage.error('删除附件失败，请稍后重试');
  }
};

const deleteExam = async () => {
  try {
    const response = await axios.delete(`/backend/api/exam/${examToDelete.value}/delete/`, {
      withCredentials: true,
    });
    if (response.status === 200) {
      ElMessage.success('考试删除成功');
      deleteDialogVisible.value = false;
      await fetchExams();
    }
  } catch (error) {
    console.error('删除考试失败:', error);
    ElMessage.error('删除考试失败，请稍后重试');
  }
};

// 修改viewExamDetail函数
const viewExamDetail = async (examId) => {
  try {
    loading.value = true;
    const response = await axios.get(`/backend/api/exam/${examId}/`, {
      withCredentials: true,
    });
    examDetail.value = response.data;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取考试详情失败:', error);
    ElMessage.error('获取考试详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 添加处理关闭详情弹窗的函数
const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false;
  examDetail.value = null;
};



// 修改打开上传扫描件函数
const openUploadScanDialog = async (examId) => {
  currentExamId.value = examId;
  try {
    const response = await axios.get(`/backend/api/exam/${examId}/submission_status/`, {
      withCredentials: true
    });
    submissionList.value = response.data;
    submissionDialogVisible.value = true;
  } catch (error) {
    console.error('获取提交状态列表失败:', error);
    ElMessage.error('获取提交状态列表失败，请稍后重试');
  }
};

// 4. 添加处理函数
const handleUploadScan = (submission) => {
  currentSubmission.value = submission;
  uploadScanDialogVisible.value = true;
};

const handleGrade = (submission) => {
  currentSubmission.value = submission;
  gradingDialogVisible.value = true;
};

const handleGraded = async () => {
  // 重新获取提交状态列表
  await openUploadScanDialog(currentExamId.value);
  ElMessage.success('评分已保存');
};

const handleViewSubmission = (submission) => {
  currentSubmission.value = submission;
  submissionDetailDialogVisible.value = true;
};

const handleUploadedScan = async () => {
  // 重新获取提交状态列表
  await openUploadScanDialog(currentExamId.value);
  ElMessage.success('扫描件上传成功');
};

// 修改confirmDeleteExam函数
const confirmDeleteExam = (examId) => {
  examToDelete.value = examId;
  deleteDialogVisible.value = true;
};

onMounted(() => {
  if (props.courseId) {
    fetchExams()
  }
})
</script>

<style scoped>
.exam-container {
  padding: 20px;
}

.exam-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.exam-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.exam-date {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
}

.delete-option {
  color: #f56c6c;
}

.delete-confirmation {
  text-align: center;
  padding: 20px 0;
}

.delete-confirmation i {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 10px;
}

.delete-confirmation p {
  margin: 0;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}
</style>
